var express = require('express');
var router = express.Router();
const {userModel,development,draft,article} = require('../model/model')
var multiparty = require('multiparty');
const { log } = require('debug/src/browser');
const { randomCode, sendCode } = require('../tools/sendCode')
const jwt = require('jsonwebtoken')
const key = '2024/7/9/2/50_shaowenkai'
var nodemailer = require('nodemailer');

router.post('/lth/getPic',async(req,res)=>{
    let form = new multiparty.Form();
    form.uploadDir = './upload'
    form.parse(req,async(err,a,imgUrl)=>{
        res.send({
            code:200,
            imgUrl:'http://127.0.0.1:3000/'+imgUrl.file[0].path
        })
    })
})

router.post('/lth/pushDeve',async(req,res)=>{
    let data = req.body
    console.log(data);
    await development.create(data)
    res.send({
        code:200,
        msg:'上传成功'
    })
})

router.post('/lth/pushDraft',async(req,res)=>{
    let data = req.body
    await draft.create(data)
    res.send({
        code:200,
        msg:'保存成功'
    })
})

router.post('/lth/pushArticle',async(req,res)=>{
    let data = req.body
    console.log(data);
    await article.create( data)
    res.send({
        code:200,
        msg:'文章发布成功'
    })
})

router.get('/lth/getDraft',async(req,res)=>{
    let data = await draft.find()
    res.send({
        code:200,
        data,
        length:data.length
    })
})
router.post('/lth/delMany',async(req,res)=>{
    let data = req.body
    console.log(data);
    await draft.deleteMany({_id:{$in:data}})
    res.send({
        code:200,
        msg:'删除成功'
    })
})
//发送验证码
router.post('/sendCode', async (req, res) => {
    let { phone } = req.body;
    let code = randomCode(4);//生成4位数字随机验证码
    sendCode(phone, code, function (success) {
        if (success) {
            res.send({
                code: 200,
                msg: "短信验证码已发送!,请查收",
                data: code
            });
        } else {
            res.send("短信验证码发送失败");
        }
    })
})
//手机号登入
router.post('/phoneLogin', async (req, res) => {
    let { phone } = req.body
    let user = await userModel.findOne({ phone })
    let token = null
    if (!user) {
        userModel.create({ phone })
        user = await userModel.findOne({ phone })
    }
    token = 'Bearer ' + jwt.sign({ ...user }, key, { expiresIn: '6h' })
    res.send({
        code: 200,
        msg: "登入成功",
        data: user,
        token
    })
})

//账号登入
router.post('/PsswordLoginAPI', async (req, res) => {
    let { phone, password } = req.body
    let user = await userModel.findOne({ $or: [{ phone }, { email: phone }], password })
    let token = 'Bearer ' + jwt.sign({ ...user }, key, { expiresIn: '6h' })
    if (user) {
        res.send({
            code: 200,
            msg: "登入成功",
            data: user,
            token
        })
    } else {
        res.send({
            code: 400,
            msg: "账号或密码错误",
        })
    }
})

//密码找回--短信
router.put('/updatePasswordAPI', async (req, res) => {
    let { phone, password } = req.body
    let user = await userModel.findOne({ phone })
    if (user) {
        await userModel.updateOne({ phone }, { password })
        res.send({
            code: 200,
            msg: "修改成功"
        })
    } else {
        res.send({
            code: 400,
            msg: "账号不存在!!!请先创建账号"
        })
    }

})

//密码找回--邮箱
router.put('/EmailUpdatePasswordAPI', async (req, res) => {
    let { email, password } = req.body
    let user = await userModel.findOne({ email })
    if (user) {
        await userModel.updateOne({ email }, { password })
        res.send({
            code: 200,
            msg: "修改成功"
        })
    } else {
        res.send({
            code: 400,
            msg: "账号不存在!!!请先创建账号"
        })
    }

})

//发送邮箱
router.post('/sendEmailAPI', async (req, res) => {
    let { email } = req.body
    let code = randomCode(6);//生成6位数字随机验证码
    //开启一个 SMTP 连接池
    var transport = nodemailer.createTransport({
        host: 'smtp.qq.com', //QQ邮箱的 smtp 服务器地址
        secure: true, //使用 SSL 协议
        secureConnection: false, //是否使用对 https 协议的安全连接
        port: 465, //QQ邮件服务所占用的端口
        auth: {
            user: '2415927967@qq.com', //开启 smtp 服务的发件人邮箱，用于发送邮件给其他人
            pass: 'aiofexockustdhic' //SMTP 服务授权码
        }
    })
    var mailOption = {
        from: '2415927967@qq.com', //发件人
        to: email, //收件人
        subject: '讯闻邮箱验证', //标题
        html: `<b>尊敬的用户，您在讯闻邮箱验证中，本次的验证码为：${code}!,请在5分钟内完成验证</b>` //正文，可使用 HTML 格式进行渲染
    }
    await transport.sendMail(mailOption, (err, result) => {
        if (err) {//执行错误
            res.send({
                code: 400,
                msg: "发送失败"
            })
        } else {
            res.send({
                code: 200,
                msg: "发送成功!，请查收",
                data: code
            })//执行成功， 会返回响应体内容。
        }
        transport.close(); // 如果没用，则关闭连接池
    })
})


module.exports = router;
